package hydrap2p.helper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.dtools.ini.AdvancedIniFile;
import org.dtools.ini.IniFile;
import org.dtools.ini.IniFileReader;
import org.dtools.ini.IniItem;
import org.dtools.ini.IniSection;

public class Utility {
	public static String getUserHome()
	{
		String userHome=System.getProperty("user.home");
		return userHome;
	}
	public static String appendPath(String start, String next)
	{
		return start+File.separator+next;
	}
	public static String getUserConfigurationPath()
	{
		return appendPath(getUserHome(),"hydrap2p");
	}
	/**
	 * If on Windows
	 * 		Try to return %ProgramFiles%\HydraP2P, which should be where we're installed
	 * 		Otherwise, return CurrentWorkingDirectory\conf
	 * Else
	 * 		Return /etc/hydrap2p
	 * @return
	 */
	public static String getSharedConfigurationPath()
	{
		String osName = System.getProperty("os.name");
		String shared="";
		String filePath="";
		if (osName.toLowerCase().indexOf("windows") > -1)
		{
			shared=System.getenv("ProgramFiles");		// get Program Files
			filePath=appendPath(shared,"HydraP2P");
			if (!new File(filePath).isDirectory())
			{
				shared=System.getProperty("user.dir");		// get current working directory
				filePath=appendPath(shared,"conf");
			}
		}
		else
		{
			shared="/etc";
			filePath=appendPath(shared,"hydrap2p");
			if (!new File(filePath).isDirectory())
			{
				shared=System.getProperty("user.dir");		// get current working directory
				filePath=appendPath(shared,"conf");
			}
		} 
		return filePath;
	}
	
	public static int getManagerPort() throws NumberFormatException, FileNotFoundException
	{
		int port=-1;
		String confLocation=Utility.appendPath(Utility.getUserHome(),"hydrap2p");
		String myconfLocation=Utility.appendPath(confLocation,"servicemanager.ini");
		File myconf = new File(myconfLocation);
		if (!myconf.exists())
		{
			String sharedconfLocation=Utility.appendPath(getSharedConfigurationPath(), "servicemanager.ini");
			File sharedconf = new File(sharedconfLocation);
			if (!sharedconf.exists())
				throw new FileNotFoundException(myconfLocation);
			else
				myconf=sharedconf;
		}
		IniFile conf = new AdvancedIniFile();
		try {
			new IniFileReader(conf,myconf).read();
		} catch (IOException e) {	// could not open the file
			throw new FileNotFoundException(myconfLocation);
		}
		IniSection section=conf.getSection("main");
		if (section!=null)
		{
			IniItem temp=section.getItem("port");
			String temp2=temp.getValue();
			try {
				port=Integer.parseInt(temp2);
			}
			catch (NumberFormatException e)
			{
				throw new NumberFormatException("Port configuration could not be parsed");
			}
		}
		return port;
	}
}
